package com.cl.unipay4j.wx.pay;

import com.cl.unipay4j.core.IPayConfig;
import com.cl.unipay4j.core.Result;
import com.cl.unipay4j.core.UnipayConst;
import com.cl.unipay4j.core.pay.IClose;
import com.cl.unipay4j.wx.AbstractWxPay;
import com.cl.unipay4j.wx.sdk.WXPayConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 *以下情况需要调用关单接口：商户订单支付失败需要生成新单号重新发起支付，要对原订单号调用关单，避免重复支付；
 * 系统下单后，用户支付超时，系统退出不再受理，避免用户继续，请调用关单接口。
 *
 * 注意：订单生成后不能马上调用关单接口，最短调用时间间隔为5分钟。
 * @Author Small
 * @Date 2020/7/27 18:00
 * @Version 1.0
 **/
@Slf4j
public class WxPayClose extends AbstractWxPay implements IClose {

    public WxPayClose() {
    }

    public WxPayClose(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 关闭订单
     *
     * @param outTradeNo  平台支付流水号
     * @return
     */
    @Override
    public Result execClose(String outTradeNo) {
        log.info("WxClose::=>关闭订单请求到达,订单号{}", outTradeNo);
        try {
            Map<String, String> param = new HashMap<>();
            param.put("out_trade_no", outTradeNo);
            Map<String, String> r = initWxPay().closeOrder(param);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                String resultCode = r.get(WXPayConstants.RESULT_CODE);
                if (UnipayConst.SUCCESS.equals(resultCode)) {
                    log.info("WxClose::=>关闭订单请求成功,订单号{}", outTradeNo);
                    return Result.tradeSuccess(r);
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxClose::=>关闭订单请求失败,订单号{}，错误代码{}，错误原因{}", outTradeNo, errCode, errCodeDes);
                    return Result.returnFail(errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxClose::=>关闭订单失败,订单号{}，错误代码{}，错误原因{}", outTradeNo, returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }
        } catch (Exception e) {
            log.warn("WxClose::=>关闭订单异常,订单号{}", outTradeNo, e);
        }
        return Result.exception();
    }
}
